<!--外部指标管理-营业员员-->
<template>
	<div>
		<div class="query-form">
			<yd-form ref="myForm" :options="formOptions" :model="queryParams">
				<template #form-btn>
					<div>
						<el-button class="yd-form-btn" type="primary" @click="handlerQuery()">查询</el-button>
					</div>
				</template>
			</yd-form>
		</div>
		<!-- 数据列表 -->
		<YdTable
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="queryList"
			@currentChangeHandler="queryList"
			@sortChangeHandler="queryList"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 新增修改 -->
		<el-dialog :title="title" v-model="open" width="600px" append-to-body center>
			<el-form ref="empForm" :model="form" :rules="rules" label-width="80px">
				<el-form-item label-width="100px" label="营业员编号" prop="num">
					<el-input v-model="form.num" maxlength="50" />
				</el-form-item>
				<el-form-item label-width="100px" label="营业员名称" prop="name">
					<el-input v-model="form.name" maxlength="50" />
				</el-form-item>
				<el-form-item label-width="100px" label="营业厅编号" prop="businessHallNum">
					<el-input v-model="form.businessHallNum" maxlength="50" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>

		<!-- 上传upload -->
		<el-dialog title="营业员信息模板导入" v-model="uploadOpen" width="600px" append-to-body center>
			<div style="text-align: center">
				<el-row>
					<el-button size="small" type="primary" @click="handlerDownloadTemplate">下载模板</el-button>
				</el-row>
				<div style="margin-top: 20px">
					<el-upload
						action="#"
						:limit="1"
						accept=".xlsx,.xls"
						:on-success="handlerSuccess"
						:on-change="fileChange"
						:on-remove="handlerRemove"
						:on-error="handlerError"
						:file-list="fileList"
						:auto-upload="false"
					>
						<el-button size="small" type="primary">上 传</el-button>
					</el-upload>
				</div>
			</div>
			<template #footer>
				<el-button type="primary" @click="submitUploadForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="OutsideBusinessPersonnel" lang="ts">
import { getList, getById, deleteAll, save, edit, getTemplate, upload } from '@/api/admin/indicatorsManage/employee';
import { downloadFromBlob } from '@/utils/common';
import { getCurrentInstance, reactive, ref, toRefs } from 'vue';

const { proxy }: any = getCurrentInstance();

// 选中数组
const ids: any = ref([]);
const open = ref(false);
const uploadOpen = ref(false);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 加载层
const loading = ref(true);
//弹出层标题
const title = ref('');
const formOptions = reactive<FormOptionType>([
	{
		type: 'input',
		label: '营业员编号',
		prop: 'num',
		placeholder: '请输入营业员编号',
		attrs: {
			clearable: true,
		},
	},
	{
		type: 'input',
		label: '营业员名称',
		prop: 'name',
		placeholder: '请输入营业员名称',
		attrs: {
			clearable: true,
		},
	},
	{
		type: 'input',
		label: '营业厅编码',
		prop: 'businessHallNum',
		placeholder: '请输入营业厅编码',
		attrs: {
			clearable: true,
		},
	},
]);
// 表单校验
const rules = ref({
	num: [{ required: true, message: '营业员编号不能为空', trigger: 'blur' }],
	name: [{ required: true, message: '营业员名称不能为空', trigger: 'blur' }],
	businessHallNum: [{ required: true, message: '营业厅编号不能为空', trigger: 'blur' }],
});
// 表单参数
const data = reactive<any>({
	form: {},
});
const { form }: any = toRefs(data);
// 营业员信息列表配置
let tableConfig = reactive<any>({
	url: getList,
	columns: [
		{
			label: '营业员编号',
			prop: 'num',
			showOverFlowToolTip: true,
		},
		{
			label: '营业厅编号',
			prop: 'businessHallNum',
			showOverFlowToolTip: true,
		},
		{
			label: '营业员名称',
			prop: 'name',
			showOverFlowToolTip: true,
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['outside:businessPersonnel:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['outside:businessPersonnel:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['outside:businessPersonnel:delete'], disable: 'multiple', handler: () => deleteHandle() },
		{ name: '模板导入', icon: 'yd-icon-import', permi: ['outside:businessPersonnel:import'], handler: () => uploadHandle() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 营业员信息列表数据
let tableData = reactive<any>({
	data: [],
	total: 0,
});
//营业员信息查询参数
let queryParams = reactive<any>({
	pageNum: 1,
	pageSize: 10,
});
const fileList: any = ref([]);

/** 查询返回码列表 */
function queryList() {
	tableConfig.loading = true;
	getList(queryParams)
		.then((response: ApiResponse | any) => {
			tableData.data = response.data.records;
			tableConfig.pagination.total = response.data.total;
			tableConfig.loading = false;
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
/** 返回码搜索按钮操作 */
function handlerQuery() {
	queryList();
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	title.value = '新增营业员信息';
	open.value = true;
}
/** 修改按钮操作 */
function updateHandle() {
	reset();
	title.value = '编辑营业员信息';
	const id: any = ids.value;
	getById(id).then((response) => {
		form.value = response.data[0];
		open.value = true;
	});
}
/** 删除按钮操作 */
function deleteHandle() {
	proxy.$modal
		.confirm('确定删除?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteAll(ids.value).then((res: ApiResponse | any) => {
				if (res.code === 0) {
					// 删除后的总条数
					let totalCount = tableConfig.pagination.total - ids.value.length;
					// 计算删除后的总页数
					let totalPage = Math.ceil(totalCount / queryParams.pageSize);
					// 如果删除后的总页数小于1, 置为1
					totalPage = totalPage < 1 ? 1 : totalPage;
					// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
					queryParams.pageNum = queryParams.pageNum > totalPage ? totalPage : queryParams.pageNum;
					proxy.$modal.msgSuccess('删除成功');
					handlerQuery();
				} else {
					proxy.$modal.msgWarning(res.msg);
				}
			});
		})
		.catch(() => {});
}
/** 模板导入 */
function uploadHandle() {
	fileList.value = [];
	uploadOpen.value = true;
}
/*下载模板*/
function handlerDownloadTemplate() {
	getTemplate().then((response) => {
		downloadFromBlob(response, '营业员信息表模板');
	});
}
function fileChange(file: any) {
	fileList.value[0] = file.raw;
}
function handlerRemove() {
	fileList.value = [];
}
function handlerSuccess() {
	proxy.$modal.msgSuccess('上传成功，点击确认导入!');
}
function handlerError() {
	proxy.$modal.msgError('上传失败');
}
/** 导入提交按钮 */
function submitUploadForm() {
	if (fileList.value[0]) {
		let form = new FormData();
		const isXLS =
			fileList.value[0].type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
			fileList.value[0].type === 'application/vnd.ms-sheet' ||
			fileList.value[0].type === 'application/vnd.ms-excel';
		if (!isXLS) {
			proxy.$modal.msgError('请上传Excel文件');
			return;
		}
		const isLt5M = fileList.value[0].size / 1024 / 1024 < 5;
		if (!isLt5M) {
			proxy.$modal.msgError('文件大小不能超过5M!');
		} else {
			form.append('file', fileList.value[0]);
			upload(form).then((rs: ApiResponse | any) => {
				if (rs.code === 0) {
					proxy.$modal.msgSuccess(rs.data);
					handlerQuery();
					uploadOpen.value = false;
				} else {
					proxy.$modal.msgError(rs.msg);
				}
			});
		}
	} else {
		proxy.$modal.msgError('请先上传文件');
	}
}
/** 确认提交按钮 */
function submitForm() {
	proxy.$refs['empForm'].validate((valid: boolean) => {
		if (valid) {
			let api = form.value.id ? edit : save;
			api(form.value).then((response: ApiResponse | any) => {
				if (response.code === 0) {
					if (form.value.id !== undefined) {
						proxy.$modal.msgSuccess('修改成功');
					} else {
						proxy.$modal.msgSuccess('新增成功');
					}
					open.value = false;
					queryList();
				} else {
					proxy.$modal.msgError(response.msg);
				}
			});
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	uploadOpen.value = false;
}
function reset() {
	form.value = {};
	// proxy.resetForm('empForm');
}
// 多选框选中数据
function handlerSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
queryList();
</script>
